/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.servlets;

import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.LinkedHashSet;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dhpollack.rotogss.data.RotoGSSTeams;
import com.dhpollack.rotogss.data.RotoGSSUsers;
import com.dhpollack.rotogss.helper.PMF;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * @author davidpl
 *
 */
public class YahooOAuthReturnServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5634121026169508632L;

	protected void service(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        String authdata = "";
        
        try {
        	authdata = URLDecoder.decode(req.getParameter("authdata"), "US-ASCII");
        } catch(NullPointerException e) {
        	log("No authdata parameter found");
            resp.sendRedirect("/start.jsp");
            return;
        }
        
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        Queue queue = QueueFactory.getDefaultQueue();
        try {
        	tx.begin();
            Key userkey = new KeyFactory.Builder(RotoGSSUsers.class.getSimpleName(),user.getNickname()).getKey();
            RotoGSSUsers rotouser;
            try {
            	log("Find User");
                rotouser = pm.getObjectById(RotoGSSUsers.class, userkey);
            } catch(JDOObjectNotFoundException e) {
            	log("User Not Found.  Being Created...");
            	rotouser = new RotoGSSUsers();
            	rotouser.setGoogleUserKey(userkey);
            	rotouser.setYahooGamesTracked(new LinkedHashSet<Key>());
            	rotouser.setYahooTeamsTracked(new LinkedHashSet<RotoGSSTeams>());
            }
            if(authdata.length() > 1) {
            	rotouser.setYahooOAuthData(authdata);
            } else {
            	log("Authdata too short to save\nAuthdata: " + authdata);
            }
        	pm.makePersistent(rotouser);
            queue.add(
            		DatastoreServiceFactory.getDatastoreService().getCurrentTransaction(),
            		url("/admin/yahooGetGames").param("user", user.getNickname())
            		);
            
        	tx.commit();
        } finally {
        	if(tx.isActive()) {
        		tx.rollback();
        	}
        }
        
        resp.sendRedirect("/start.jsp");
        
	}


}
